﻿#region Using

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dictionary.Tools;

#endregion

namespace Dictionary {
    public partial class MainForm : Form {
        #region Properties

        public List<string> Words { get; set; }

        #endregion

        #region Init

        // constructor
        public MainForm() {
            InitializeComponent();
            Init();
        }

        public void Init() {
            textBox1.Focus();
            lWordList.Sorted = true;
            UpdateWords(0, null);
            // Events
            thêmTừToolStripMenuItem.Click += Button2Click;
            sửaTừToolStripMenuItem.Click += Button3Click;
            đổiTênToolStripMenuItem.Click += Button5Click;
            xóaTừToolStripMenuItem.Click += Button4Click;
        }

        #endregion

        #region Events

        /// <summary>
        ///   Open to add more words
        /// </summary>
        private void Button2Click(object sender, EventArgs e) {
            var addForm = new ModifyWordForm(null, null, "Add", this);
            addForm.Show();
        }

        /// <summary>
        ///   Open to update word
        /// </summary>
        private void Button3Click(object sender, EventArgs e) {
            if (lWordList.Items.Count == 0) return;
            // Get Spec Value for languages

            // get selected word
            string word = lWordList.SelectedItem.ToString();
            List<string> words = Controller.Controller.GetRelateWords(word);
            string commonValue = Controller.Controller.GetCommonValueOf(word);
            commonValue = commonValue.Replace('|', '\n');
            var addForm = new ModifyWordForm(commonValue, words, "Change", this);
            addForm.Show();
        }

        private void LWordListSelectedIndexChanged(object sender, EventArgs e) {
            // Get the selected tab
            TabControl tabControl = tabControl1;
            RichTextBox rtb = null;
            switch (tabControl.SelectedTab.Text) {
                case "English":
                    rtb = rEng;
                    break;
                case "Russian":
                    rtb = rRus;
                    break;
                case "Vietnamese":
                    rtb = rVi;
                    break;
            }
            // clear the richtextbox first
            if (rtb != null) rtb.Clear();
            string selectedWord = lWordList.SelectedItem.ToString();
            string value = Controller.Controller.GetCommonValueOf(selectedWord);
            ParseHelper.ParseValue(value, ref rtb);
        }

        /// <summary>
        ///   If search string changed, we filter the list.
        /// </summary>
        private void TextBox1TextChanged(object sender, EventArgs e) {
            List<string> newList = Words.FindAll(delegate(string str)
                                                     {
                                                         string convertedWord = ConvertToUnSign(str);
                                                         return convertedWord.Contains(textBox1.Text);
                                                     });
            lWordList.DataSource = newList;
            // focus to the first word
            if (lWordList.Items.Count > 0)
                lWordList.SetSelected(0, true);
        }

        private void Button4Click(object sender, EventArgs e) {
            if (lWordList.Items.Count == 0) return;
            switch (MessageBox.Show(@"Bạn có thật sự muốn xóa từ này không?",
                                    @"Xóa từ",
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question)) {
                                        case DialogResult.Yes: {
                                            string word = lWordList.SelectedItem.ToString();
                                            Controller.Controller.DisableWord(word);
                                            // After disable in database, remove in lWordList and set selected
                                            if (lWordList.Items.Count > 0)
                                                lWordList.SetSelected(0, true);
                                            DeleteWordInList(word);
                                        }
                                            break;
            }
        }

        /// <summary>
        ///   Open a form to change word name if click Change word button
        /// </summary>
        private void Button5Click(object sender, EventArgs e) {
            if (lWordList.Items.Count == 0) return;
            string word = lWordList.SelectedItem.ToString();
            var frm = new ChangeWordForm(word, this);
            frm.Show();
        }

        private void LanguageTabSelectedChanged(object sender, EventArgs e) {
            string word;
            if (lWordList.Items.Count > 0)
                word = lWordList.SelectedItem.ToString();
            else return;
            var tab = (TabControl) sender;
            switch (tab.SelectedTab.Text) {
                case "English": {
                    UpdateWords(1, word);
                }
                    break;
                case "Russian": {
                    UpdateWords(2, word);
                }
                    break;
                case "Vietnamese": {
                    UpdateWords(3, word);
                }
                    break;
            }
        }

        private void giớiThiệuToolStripMenuItem_Click(object sender, EventArgs e) {
            MessageBox.Show("nXqd - 2011 \nFeel free to contact me: Nxqd3051990@gmail.com", @"Tác giả");
        }

        #endregion

        #region Public Methods

        public void ChangeWordInList(string oldWord, string newWord) {
            if (oldWord == newWord) return;
            int index = Words.FindIndex(s => s == oldWord);
            if (index != -1)
                Words[index] = newWord;
            lWordList.DataSource = Words;
            Refresh();
        }

        public void AddWordToList(string word) {
            if (Words.Find(s => s == word) != null) return;
            Words.Add(word);
            lWordList.DataSource = Words;
            Refresh();
        }

        public void Refresh() {
            ((CurrencyManager) lWordList.BindingContext[lWordList.DataSource]).Refresh();
        }

        #endregion

        #region Helper

        public void DeleteWordInList(string word) {
            int removeIndex = Words.FindIndex(s => s == word);
            Words.RemoveAt(removeIndex);
            Refresh();
        }

        // Change Signed Vietnamese to Unsigned
        public string ConvertToUnSign(string s) {
            string stFormD = s.Normalize(NormalizationForm.FormD);
            var sb = new StringBuilder();
            foreach (char t in from t in stFormD
                               let uc = CharUnicodeInfo.GetUnicodeCategory(t)
                               where uc != UnicodeCategory.NonSpacingMark
                               select t) {
                sb.Append(t);
            }
            sb = sb.Replace('Đ', 'D');
            sb = sb.Replace('đ', 'd');
            return (sb.ToString().Normalize(NormalizationForm.FormD));
        }

        private void UpdateWords(int langId, string key) {
            if (langId == 0) {
                lWordList.Items.Clear();
                Words = Controller.Controller.GetWords(0);
                lWordList.DataSource = Words;
            }
            else if (key == null) {
                lWordList.SelectedIndex = 0;
            }
            else {
                string word = Controller.Controller.GetRelateWord(langId, key);
                int index = lWordList.FindString(word);
                lWordList.SetSelected(index != -1 ? index : 0, true);
            }
        }

        #endregion
    }
}